require('./db/mongodb').load();
const mongoose = require('mongoose');
const express = require('express');
const multiparty = require('connect-multiparty');
// const multipartMiddleware = multiparty();
const app = express();
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const config=require('./config');

if(!config.debug){
    const https = require('https');
    const privateKey = fs.readFileSync('./cert/gongju/4182816_gongju.073c.com.key');
    const certificate = fs.readFileSync('./cert/gongju/4182816_gongju.073c.com.pem');
    const credentials = {key: privateKey, cert: certificate};
    const httpsServer = https.createServer(credentials, app);
    httpsServer.listen(config.web.sslPort, function () {
        console.log('HTTPS Server is running on: https://localhost:%s', config.web.sslPort);
    });
}else{
    const http = require('http');
    const httpServer = http.createServer(app);
    httpServer.listen(config.web.webPort, function () {
        console.log('HTTP Server is running on: http://localhost:%s', config.web.webPort);
    });
}

app.use(express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    res.data = function (data) {
        this.json({code: 200, data: data});
    };
    next();
});


app.get('/user',async function(req,res,next){
    try{
        console.log(req.query);
        const UserModel=mongoose.models['User'];
        let user=await UserModel.findById(req.query.login_id);
        if(!user||user.token!=req.query.login_token){
            throw new Error(`用户登陆验证失败:${JSON.stringify(req.query)}`);
        }
        user.lastLoginTimeTick=new Date().getTime();
        req.query.self=user;
        let routers=req.query.router.split('.');
        let returnData=undefined;
        switch(routers.length){
            case 1:{
                returnData=await user[routers[0]](req.query);
                break;
            }
            case 2:{
                returnData=await user[routers[0]][routers[1]](req.query);
                break;
            }
            case 3:{
                returnData=await user[routers[0]][routers[1]][routers[2]](req.query);
                break;
            }
            case 4:{
                returnData=await user[routers[0]][routers[1]][routers[2]][routers[3]](req.query);
                break;
            }
        }
        await user.save();
        res.data(returnData);
    }catch(e){
        console.log(e);
        next(e.message);
    }
});

app.post('/user',async function(req,res,next){
    try{
        console.log(req.body);
        const UserModel=mongoose.models['User'];
        let user=await UserModel.findById(req.body.login_id);
        if(!user||user.token!=req.body.login_token){
            throw new Error(`用户登陆验证失败:${JSON.stringify(req.body)}`);
        }
        user.lastLoginTimeTick=new Date().getTime();
        req.body.self=user;
        let routers=req.body.router.split('.');
        let returnData=undefined;
        switch(routers.length){
            case 1:{
                returnData=await user[routers[0]](req.body);
                break;
            }
            case 2:{
                returnData=await user[routers[0]][routers[1]](req.body);
                break;
            }
            case 3:{
                returnData=await user[routers[0]][routers[1]][routers[2]](req.body);
                break;
            }
            case 4:{
                returnData=await user[routers[0]][routers[1]][routers[2]][routers[3]](req.body);
                break;
            }
        }
        await user.save();
        res.data(returnData);
    }catch(e){
        console.log(e);
        next(e.message);
    }
});

const UserModel=mongoose.models['User'];
// const AutoNumberModel=mongoose.models['AutoNumber'];
const WXBizDataCrypt = require('./util/WXBizDataCrypt');
const HttpHelper = require('./util/httpHelper');
const md5 = require('md5');

app.get('/user/weChatLogin',async function(req,res,next){
    let msg = req.query;
    //换取openid和sessionkey
    let sessionKeyResultStr = await HttpHelper.getLocal(`https://api.weixin.qq.com/sns/jscode2session?appid=${config.weChat.appid}&secret=${config.weChat.appsecret}&js_code=${msg.code}&grant_type=authorization_code`);
    let sessionKeyResult = JSON.parse(sessionKeyResultStr);
    console.log(sessionKeyResult);
    if (sessionKeyResult.hasOwnProperty('session_key')) {
        try {
            // let pc = new WXBizDataCrypt(config.weChat.appid, sessionKeyResult.session_key);
            // let userData = pc.decryptData(msg.encryptedData, msg.iv);
            // let re = /[^\u4e00-\u9fa5a-zA-Z0-9]/g;
            // userData.nickname = userData.nickName.replace(re, "");
            let userData={openId:sessionKeyResult.openid};
            console.log('openId',sessionKeyResult);
            let user=await UserModel.findOne({openId:userData.openId});
            if(!user) {
                // userData.id = await AutoNumberModel.getNewNumber('User');
                userData.registerTimeTick = new Date().getTime();
                userData.lastLoginTimeTick = userData.registerTimeTick;
                userData.token = md5(userData.registerTimeTick);
                user = await UserModel.create(userData);
            }else{
                //console.log('===============》1');
                Object.assign(user,userData);
                user.lastLoginTimeTick =new Date().getTime();
                user.token=md5(user.lastLoginTimeTick);
                user.loginTimes+=1;
                await user.save();
            }
            res.data({login_id:user._id,login_token:user.token});
        } catch (e) {
            console.log('登陆信息错误:',e);
           next('登录信息错误！');
        }
    } else {
        next('微信未授权！登录失败！');
    }
});

// app.use(multiparty({uploadDir:'./public/upload/mp3' }));
//
// app.post('/upload',multipartMiddleware, function (req,res) {
//     console.log('上传文件',req.body.fileName);
//     let keys=Object.keys(req.files);
//     let source = fs.createReadStream(req.files[keys[0]].path);
//     let fileName=req.body.fileName;
//     let dest = fs.createWriteStream('./public/upload/mp3/'+fileName);
//     source.pipe(dest);
//     source.on('end', function() { fs.unlinkSync(req.files[keys[0]].path);});   //delete
//     source.on('error', function(err) {  });
//     res.json({fileName:fileName});
// });

app.use(function (err, req, res, next) {
    res.json({code: 500, msg: err});
});
app.use(function (req, res, next) {
    res.json({code: 500, msg: 'no such router'});
});

//require('./util/novelThief').run();